#pragma once
#include <osg/Drawable>

/**@note using `glDrawArraysInstanced` must set `glVertexAttribDivisor(index, 1)` first to let it take effect! */
class InstancedDrawCallback : public osg::Drawable::DrawCallback {
public:
	InstancedDrawCallback(GLuint attribIndex): m_attribIndex(attribIndex) {}

	//~InstancedDrawCallback() { std::cout << __FUNCTION__ << std::endl; }

	void drawImplementation(osg::RenderInfo& renderInfo, const osg::Drawable* drawable) const override {
		osg::GLExtensions* glExt = renderInfo.getState()->get<osg::GLExtensions>();
		bool isValid = glExt && glExt->glVertexAttribDivisor;

		if (isValid) glExt->glVertexAttribDivisor(m_attribIndex, 1);// modify the rate at which generic vertex attributes advance during instanced rendering
		
		drawable->drawImplementation(renderInfo);// default

		if (isValid) glExt->glVertexAttribDivisor(m_attribIndex, 0);// restore
	}

private:
	GLuint m_attribIndex;
};